<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

require_once('src/facebook.php');
	
class Users extends CI_Controller {

	
    function __construct() {

        parent::__construct();
		/*--------------THEMES-----------------------*/
		$this->config->load('themes');
		$theme = $this->config->item('users');
		if($theme == "" || !isset($theme))
			$theme = $this->config->item('global_theme');
			
		$this->data['css_dir'] = base_url()."assets/themes/".$theme."/css/";
		$this->data['js_dir'] = base_url()."assets/themes/".$theme."/js/";		
		$this->theme = $theme;
		$this->data['logged_in'] = $this->session->userdata('user_logged');
		$this->data['ptmenu'] = $this->load->view('common/pt_menu',$this->data,true);
		//------------------------------------------------------------------------------
        $this->load->library("email");		
		$this->load->model("google_login");	
		$this->load->model("facebook_login");	
		$this->load->model("user_model");
		$this->data['title'] = "Login/Signup";
		
		$this->data['notifications'] = Array();
		
		$this->data['members'] = $this->data_fetcher->fetch_table('tb_mas_members',null,null,Array('fk-tb_mas_bands'=>$this->session->userdata('intID')));
		if(count($this->data['members']) < 3)
				array_push($this->data['notifications'],'You have not met the minimum required number of band members(3) yet.');
		
		
		$vtest = $this->session->userdata('strVideoFileName');
		if(!isset($vtest) || $vtest == '')
			array_push($this->data['notifications'],'You have not uploaded a video yet.');
			
		$this->data['main_menu'] = $this->load->view('common/main_menu',$this->data,true);		
		
    }
	
	public function index()
	{
	
	}

    // Login and Authentication
    public function auth() {

        

        if (isset($_POST)) {

            $authentication = $this->user_model->authenticate($this->input->post('strEmail'),$this->input->post('strPass'));
            // Create User Object If Logged In Correctly
        } else {

            $authentication = false;
        }

        // This can be simplified a LOOOT!
        if ($authentication == 1) {

            echo 1;
        } else {

            echo 0;
        }
    }

    public function logout() {

        $this->session->sess_destroy();        		
        redirect(base_url());
    }

    function register() {        
        $post = $this->input->post();
        $result = $this->user_model->register_user($post);
        $response['success'] = $result;

        if ($result == 1)
            $response['message'] = "Your username has been registered check your email for confirmation";
        else if ($result == 0)
            $response['message'] = "The email address you entered may already be in use";
        else
            $response['message'] = "The username you entered may already be in use";

        echo json_encode($response);
    }

    function forgot() {
        $email = $this->input->post("email");        

        $data = array(
            'strEmail' => $email
        );

        $result = $this->user_model->create_reset_request($data);

        // Check if email exists
        if ($result) {

            echo "1";
        } else {

            echo "0";
        }
    }

    function password_reset($hash) {        

        $data['hash'] = $hash;

        if ($_POST) {

            $data = array(
                'hash' => $hash,
                'password' => $this->input->post('password')
            );

            $this->user_model->reset_password($data);						
            $this->data['message'] = "Your password has been reset!.";
        }
		
		
		$this->data['hash'] = $data['hash'];
        $this->data['title'] = "Pinoytuner - Reset Your Password ";

        //assigns all userdata from session if exists
        foreach ($this->session->userdata as $key => $value) {
            $data[$key] = $value;
        }
				

        $this->load->view('common/header', $this->data);		
        $this->load->view('password_reset', $this->data);
		$this->load->view('common/footer',$this->data);			
        
    }

    function confirm_email($hash) {        
        $this->user_model->validate_hash($hash);
    }

    function google_signin() {        

        if (isset($_GET['openid_sig'])) {

            $user_data = array(
                'strEmail' => $_GET['openid_ext1_value_email'],
                'strFirstname' => $_GET['openid_ext1_value_firstname'],
                'strLastname' => $_GET['openid_ext1_value_lastname']
            );

            $result = $this->user_model->register_user($user_data);


            if ($result == 1) {
                // New User
                // Bypass reset confirm email, reset pass etc
                $user_data['strConfirmed'] = 1;
                $user_data['strReset'] = 1;
                $user_data['strUsername'] = $user_data['strEmail'];
            } else {
                // User Exists
                // Bypass reset confirm email, reset pass etc
                $user_data['strConfirmed'] = 1;
                $user_data['strReset'] = 1;	
				$this->data['redirect'] = base_url();
				$this->load->view('refresh_parent',$this->data);	
            }

            $this->user_model->update_user($user_data['strEmail'], $user_data);
            $this->user_model->authenticate($user_data);			

        } else {

            redirect(base_url() . "users/google_signup_fail");
        }
    }

    function google_signup_fail() {        

        $data['page_title'] = "Development: Welcome to the Pinoytuner Online Store - Login with Google";
        $data['google_login'] = $this->google_login->google_signin();

        $this->load->view('common/header', $data);
        $this->load->view('templates/google_signup_fail');
        $this->load->view('common/header', $data);
    }
	
	public function fb_login()
	{
		$this->fb_connect();
		$this->data['redirect'] = base_url(); 
		$this->load->view('refresh_parent',$this->data);	
	}
	
	public function fb_connect()
	{
		$this->load->model('data_fetcher');
		$this->load->model('data_poster');
		$this->config->load('fbconfig');
		$app_id = $this->config->item('app_id');
		$app_secret = $this->config->item('app_secret');
			
		$facebook = new Facebook(array(
			  'appId'  => $app_id,
			  'secret' => $app_secret
			  
		));
		
		$user = $facebook->getUser();
		$facebook->setExtendedAccessToken();
		
		if($user) {
		  try{
				// Proceed knowing you have a logged in user who's authenticated.
				$user = $facebook->api('/me');
				$params = array( 'next' => base_url().'users/logoutfb' );
				$logouturl = $facebook->getLogoutUrl($params); // $params is optional. 										
				$this->session->set_userdata('logouturl',$logouturl);
				$this->session->set_userdata('getAppID',$facebook->getAppID());;
				if($user['id']!=NULL){
					$salt = 'c9s1';
					$pass = substr(pw_hash(uniqid()), 0, 8).$salt;
					strtoupper($user['gender'][0]);
					$userdata = Array(
									  'strFirstname' => $user['first_name'],
									  'strLastname' => $user['last_name'],
									  'strUsername' => $user['first_name'].$user['last_name'],									  									  
									  'strEmail' => $user['email'],
									  'dteCreated' => date("Y-m-d H:i:s"),
					);
					$test = current($this->data_fetcher->fetch_table('tb_mas_users',null,null,Array('strEmail' => $user['email'])));
					if(isset($test) && !empty($test))
					{
					
					}else
					{
						$this->data_poster->post_data('tb_mas_users',$userdata,null);
					}
					$userdata = current($this->data_fetcher->fetch_table('tb_mas_users',null,null,Array('strEmail' => $user['email'])));
					foreach($userdata as $key=>$value)
					{
						$this->session->set_userdata($key,$value);
					}
					$this->session->set_userdata('user_logged',1);					
					
				}					
			}catch (FacebookApiException $e) {
			  error_log($e);
			  $user = null;
		  }
		}
		
		if (!$user) {
			
		}
		
	}
	
	function update_mobile($id,$mobile)
	{
		$data = array('mobile_number'=>$mobile);
		$this->db->where('user_id',$id);
		$this->db->update('users',$data);
	}
	
	function login() {        		
		
		/*get facebook login link*/	
		$this->config->load('fbconfig');
		$app_id = $this->config->item('app_id');
		$app_secret = $this->config->item('app_secret');
		$facebook = new Facebook(array(
			  'appId'  => $app_id,
			  'secret' => $app_secret
			  
		));
		$params = array(
			'scope' => 'user_status,publish_stream,user_photos,email,offline_access,user_photos,user_birthday,user_location,friends_likes,read_stream',
			'redirect_uri'=>site_url('users/fb_login')
		);
		$this->data['fb_login_link'] = $facebook->getLoginUrl($params);
		/*get facebook login link end*/
		
        $this->load->view('common/header',$this->data);        
		$this->load->view('login_header_body',$this->data);
        $this->load->view('login_form',$this->data);        
		$this->load->view('common/footer',$this->data);
    }
	
	function forgot_pass() {             
        $this->load->view('common/header');        
		$this->load->view('login_header_body',$this->data);
        $this->load->view('forgot');  
		$this->load->view('common/footer');	
		$this->load->view('signup_js');
    }

    function signup() {
		$this->data['locations'] = $this->data_fetcher->fetch_table('tb_mas_regions');
	
        $this->load->view('common/header');        
		$this->load->view('login_header_body',$this->data);
        $this->load->view('signup',$this->data);
		$this->load->view('common/footer');	        
		$this->load->view('signup_js');
    }
	
	function addmember() {
		$test = $this->session->userdata('user_logged');
		if($test)
		{
			$this->load->view('common/header');
			$this->load->view('login_header_body',$this->data);
			$this->load->view('addmember');
			$this->load->view('common/footer');
			$this->load->view('addmember_js');
		}
		else
		{
			redirect(base_url().'login');
		}
	}
	
	function edit_profile() {
		$test = $this->session->userdata('user_logged');
		$this->data['error'] = $this->session->flashdata('error');
		$this->data['title'] = "Edit Profile";
		if($test)
		{
			$this->data['notifications'] =  Array();
			$this->data['members'] = $this->data_fetcher->fetch_table('tb_mas_members',null,null,Array('fk-tb_mas_bands'=>$this->session->userdata('intID')));
			$this->data['cur_location'] = $this->session->userdata('fk-tb_mas_regions');
			print_r($this->data['cur_location']);
			$this->data['profile'] = $this->user_model->get_band_info($this->session->userdata('intID'));
			$this->data['locations'] = $this->data_fetcher->fetch_table('tb_mas_regions');
			$this->load->view('common/header',$this->data);
			$this->load->view('login_header_body',$this->data);
			$this->load->view('editprofile',$this->data);
			$this->load->view('common/footer');
			$this->load->view('editprofile_js');
			$this->load->view('uploadify_js',$this->data);
		}
		else
		{
			redirect(base_url().'login');
		}
	}
	
	function add()	{
		$post = $this->input->post();
		$post['fk-tb_mas_bands'] = $this->session->userdata('intID');
		$s = $post['dteBirthdate'];
		$date = strtotime($s);
		$date = date('Y-m-d',$date);
		$post['dteBirthdate'] = $date;
		$result = $this->user_model->add_member($post);
		$response['success'] = $result;

		if ($result == 1)
			$response['message'] = "Your member has been added.";
		else
			$response['message'] = "The member you entered may already have been added previously.";
		
		echo json_encode($response);
	}
	
	function delete() {
		$post = $this->input->post();
		$post['fk-tb_mas_bands'] = $this->session->userdata('intID');
		$result = $this->user_model->delete_member($post);
		$response['success'] = $result;

		if ($result == 1)
			$response['message'] = "Your member has been deleted.";
		else
			$response['message'] = "The member you entered may already have been added previously.";
		
		echo json_encode($response);
	}
	
	function edit_member($intID) {
		$this->data['member'] = current($this->data_fetcher->fetch_table('tb_mas_members',null,null,Array('fk-tb_mas_bands'=>$this->session->userdata('intID'),'intID'=>$intID)));
		$this->data['d'] = date_parse_from_format("Y-m-d",$this->data['member']['dteBirthDate']);
		
		$this->load->view('common/header');
		$this->load->view('login_header_body',$this->data);
		$this->load->view('editmember');
		$this->load->view('common/footer');
		$this->load->view('editmember_js');
	}
	
	function edit_member_ajax() {
		$post = $this->input->post();
		$post['fk-tb_mas_bands'] = $this->session->userdata('intID');
		$s = $post['dteBirthdate'];
		$date = strtotime($s);
		$date = date('Y-m-d',$date);
		$post['dteBirthdate'] = $date;
		$result = $this->user_model->edit_member($post);
		$response['success'] = $result;

		if ($result == 1)
			$response['message'] = "Your member's info has been edited.";
		else
			$response['message'] = "An error occured, please try again later.";
		
		echo json_encode($response);
	}
	
	function edit(){
		$post = $this->input->post();
		$post['intID'] = $this->session->userdata('intID');
		$result = $this->user_model->edit_about($post);
		$response['success'] = $result;
		
		if ($result == 1)
			$response['message'] = "Your band's profile has been edited.";
		else
			$response['message'] = "An error occured, please try again later.";
		
		echo json_encode($response);
	}
	
	public function upload_video($band_id)
	{
		if($this->session->userdata('user_logged'))
		{
			/*
			Uploadify
			Copyright (c) 2012 Reactive Apps, Ronnie Garcia
			Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
			*/

			// Define a destination
			$targetFolder = 'rhb/assets/uploads/videos'; // Relative to the root


			if (!empty($_FILES)) {	
				$tempFile = $_FILES['Filedata']['tmp_name'];
				$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
				
				
				
				// Validate the file type
				$fileTypes = array('mp4','flv'); // File extensions
				$fileParts = pathinfo($_FILES['Filedata']['name']);
				
				$targetFileName = "video_".date("ymdhis").".".$fileParts['extension'];
				$targetFile = rtrim($targetPath,'/') . '/' . $targetFileName;
				
				if (in_array(strtolower($fileParts['extension']),$fileTypes)) {
					move_uploaded_file($tempFile,$targetFile);
					$data = array(
									'intID'=>$band_id,
									'strVideoFileName'=>$targetFileName
								);
					$this->user_model->save_video($data);
					echo '1';
				} else {
					
					$this->session->set_flashdata('error','Invalid file type.');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Could not process file');
			}
			redirect(base_url().'users/edit_profile/'.$band_id);
		}
		else
		{			
			redirect(base_url().'login');
		}
		
	}
	
	public function upload_image($band_id)
	{
		if($this->session->userdata('user_logged'))
		{
			/*
			Uploadify
			Copyright (c) 2012 Reactive Apps, Ronnie Garcia
			Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
			*/

			// Define a destination
			$targetFolder = 'rhb/assets/lib/uploader/server/php/files'; // Relative to the root


			if (!empty($_FILES)) {	
				$tempFile = $_FILES['Filedata']['tmp_name'];
				$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
				
				
				
				// Validate the file type
				$fileTypes = array('jpg','png','gif'); // File extensions
				$fileParts = pathinfo($_FILES['Filedata']['name']);
				
				$targetFileName = "video_".date("ymdhis").".".$fileParts['extension'];
				$targetFile = rtrim($targetPath,'/') . '/' . $targetFileName;
				
				if (in_array(strtolower($fileParts['extension']),$fileTypes)) {
					move_uploaded_file($tempFile,$targetFile);
					$data = array(
									'intID'=>$band_id,
									'strPicture'=>$targetFileName
								);
					$this->user_model->save_image($data);
					echo '1';
				} else {
					$this->session->set_flashdata('error','Invalid file type.');
				}
				
				redirect(base_url().'users/edit_profile/'.$band_id);
			}
			else
			{
				$this->session->set_flashdata('error','Could not process file.');
			}
		}
		else
		{
			echo "you are not logged in";
		}
	}
	
	public function confirm() {
		$test = $this->session->userdata('user_logged');
		if(!$test)
		{
			$this->data['title'] = "SUCCESSFULL REGISTRATION";
			$this->load->view('common/header');
			$this->load->view('login_header_body',$this->data);
			$this->load->view('confirm',$this->data);
			$this->load->view('common/footer');
			$this->load->view('confirm_js');
		}
		else
		{
			redirect(base_url());
		}
		
	}
	
	function resend_email() {
		
		$post = $this->input->post();
		$result = $this->user_model->resend_confirmation($post);
		$response['success'] = $result;

		if ($result == 1)
			$response['message'] = "Your confirmation link has been sent to your email";
		else if ($result == 0)
			$response['message'] = "The email you entered is not yet registered.";
		else if ($result == 3)
			$response['message'] = "You have already confirmed your email. Please log in using your account.";
		else
			$response['message'] = "An error occured, please try again later.";
		
		echo json_encode($response);
	}
	
	function edit_location() {
		$post = $this->input->post();
		$data['fk-tb_mas_regions'] = $post['region'];
		$data['intID'] = $this->session->userdata('intID');
		
		$result = $this->user_model->edit_location($data);
		$response['success'] = $result;

		if ($result == 1)
			$response['message'] = "Your confirmation link has been sent to your email";
		else
			$response['message'] = "An error occured, please try again later.";
		
		echo json_encode($response);
	}

}
?>
